<template>
  <s-clean-layout :title="isEdit ? '编辑礼簿' : '添加礼簿'" navbar="normal">
    <view class="edit-container">      
      <!-- 表单内容 -->
      <view class="form-content">
        <!-- 礼簿类型 -->
        <view class="form-item">
          <view class="form-label">礼簿类型</view>
          <view class="form-value" @tap="selectGiftType">
            <text>{{ giftType }}</text>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 礼簿名称 -->
        <view class="form-item">
          <view class="form-label">礼簿名称</view>
          <view class="form-value">
            <input type="text" v-model="giftTitle" placeholder="请输入礼簿名称" />
          </view>
        </view>
        
        <!-- 宴请日期 -->
        <view class="form-item">
          <view class="form-label">宴请日期</view>
          <view class="form-value" @tap="showDatePicker">
            <text>{{ giftDate }}</text>
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 封面颜色 -->
        <view class="form-item">
          <view class="form-label">封面颜色</view>
          <view class="form-value color-selector">
            <view 
              class="color-option" 
              v-for="(color, index) in colorOptions" 
              :key="index"
              :class="{ active: selectedColor === color.value }"
              :style="{ backgroundColor: color.bg }"
              @tap="selectColor(color.value)"
            >
              <uni-icons v-if="selectedColor === color.value" type="checkmarkempty" size="16" color="#fff"></uni-icons>
            </view>
          </view>
        </view>
        
        <!-- 备注 -->
        <view class="form-item textarea-item">
          <view class="form-label">备注</view>
          <view class="form-value">
            <textarea 
              v-model="remark" 
              placeholder="选填（最多50个字）" 
              maxlength="50"
              class="remark-textarea"
            />
          </view>
        </view>
        
        <!-- 提示信息 -->
        <view class="tips-text">
          Tips: 一场宴事活动中，用来登记所有宾客礼礼的礼簿，也可根据需求建立自己的礼簿~
        </view>
      </view>
      
      <!-- 底部按钮区域 -->
      <view class="bottom-buttons">
        <view class="delete-btn" v-if="isEdit" @tap="showDeleteConfirm">
          <uni-icons type="trash" size="20" color="#fff"></uni-icons>
          <text>删除礼簿</text>
        </view>
        <view class="placeholder" v-else></view>
        <view class="confirm-btn" @tap="saveGiftBook">确定</view>
      </view>
      
      <!-- 日期选择器组件 -->
      <s-datetime-picker
        v-model:visible="datePickerVisible"
        :initial-date="giftDate || formatDate(new Date())"
        mode="date"
        title="选择宴请日期"
        @confirm="onDateConfirm"
      />
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import sheep from '@/sheep';
import GiftApi from '@/pages/money/api/gift';

// 获取路由参数
const giftId = ref(0);
const giftType = ref('收礼礼簿');
const giftTitle = ref('');
const giftDate = ref('');
const selectedColor = ref('red');
const remark = ref('');

// 日期选择器控制
const datePickerVisible = ref(false);

// 判断是编辑还是添加
const isEdit = computed(() => giftId.value > 0);

// 颜色选项
const colorOptions = [
  { value: 'red', bg: '#ff4d4f' },         // 更亮的红色
  { value: 'orange', bg: '#ff7a45' },      // 更亮的橙色
  { value: 'green', bg: '#52c41a' },       // 更亮的绿色
  { value: 'blue', bg: '#1890ff' },        // 更亮的蓝色
  { value: 'purple', bg: '#722ed1' },      // 更亮的紫色
  { value: 'gray', bg: '#8c8c8c' },        // 保持灰色
  // 新增4个亮丽的颜色
  { value: 'pink', bg: '#ff85c0' },        // 亮粉色
  { value: 'teal', bg: '#13c2c2' },        // 亮青色
  { value: 'gold', bg: '#faad14' },        // 金色
];

// 页面加载时获取路由参数
onMounted(() => {
  // 修改获取页面参数的方式，使用getCurrentPages获取当前页面实例
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const params = currentPage.options || {};
  
  // 如果有id参数，则为编辑模式
  if (params.id) {
    giftId.value = params.id;
    // 查询已有礼簿信息
    fetchGiftBookDetail(params.id);
  } else {
    // 添加模式，设置默认值
    giftType.value = params.type === 'send' ? '送礼礼簿' : '收礼礼簿';
    giftDate.value = formatDate(new Date());
  }
});

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 返回上一页 - 保留此函数但不再使用
const goBack = () => {
  sheep.$router.back();
};

// 选择礼簿类型
const selectGiftType = () => {
  uni.showActionSheet({
    itemList: ['收礼礼簿', '送礼礼簿'],
    success: function (res) {
      giftType.value = res.tapIndex === 0 ? '收礼礼簿' : '送礼礼簿';
    }
  });
};

// 显示日期选择器
const showDatePicker = () => {
  datePickerVisible.value = true;
};

// 日期选择确认
const onDateConfirm = (result) => {
  if (result && result.date) {
    giftDate.value = result.date;
  }
};

// 选择颜色
const selectColor = (color) => {
  selectedColor.value = color;
};

// 保存礼簿
const saveGiftBook = async () => {
  if (!giftTitle.value) {
    uni.showToast({
      title: '请输入礼簿名称',
      icon: 'none'
    });
    return;
  }
  
  if (!giftDate.value) {
    uni.showToast({
      title: '请选择宴请日期',
      icon: 'none'
    });
    return;
  }
  
  // 构建保存的数据
  const saveData = {
    id: giftId.value ? Number(giftId.value) : null,
    bookName: giftTitle.value,
    eventDate: new Date(giftDate.value).getTime(),
    transactionType: giftType.value === '收礼礼簿' ? 'IN' : 'OUT',
    coverColor: getColorCode(selectedColor.value),
    remark: remark.value
  };
  
  try {
    // 调用API保存数据
    const response = await GiftApi.addOrUpdateAccountBook(saveData);
    
    if (response.code === 0) {
      uni.showToast({
        title: isEdit.value ? '更新成功' : '添加成功',
        icon: 'success',
        success: function() {
          setTimeout(() => {
            sheep.$router.back();
          }, 500);
        }
      });
    } else {
      uni.showToast({
        title: response.msg || '保存失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('保存礼簿失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    });
  }
};

// 获取颜色代码
const getColorCode = (colorName) => {
  const colorMap = {
    'red': '#ff4d4f',
    'orange': '#ff7a45',
    'green': '#52c41a',
    'blue': '#1890ff',
    'purple': '#722ed1',
    'gray': '#8c8c8c',
    'pink': '#ff85c0',
    'teal': '#13c2c2',
    'gold': '#faad14'
  };
  
  return colorMap[colorName] || '#ff4d4f';
};

// 显示删除确认
const showDeleteConfirm = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该礼簿吗？',
    success: async function (res) {
      if (res.confirm) {
        try {
          // 调用删除API
          const response = await GiftApi.deleteAccountBook({
            id: giftId.value
          });
          
          if (response.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success',
              success: function() {
                setTimeout(() => {
                  // 修改：根据礼簿类型跳转到对应的列表页面
                  const isReceiveType = giftType.value === '收礼礼簿';
                  // 跳转到礼簿列表页面，并传递类型参数
                  sheep.$router.go('/pages/money/gift-book-list', {
                    type: isReceiveType ? 'receive' : 'send'
                  });
                }, 500);
              }
            });
          } else {
            uni.showToast({
              title: response.msg || '删除失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('删除礼簿失败:', error);
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
        }
      }
    },
    fail: function (res) {
      console.error('删除礼簿失败:', res);
      uni.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  });
};

// 查询礼簿详情
const fetchGiftBookDetail = async (id) => {
  try {
    // 使用正确的API接口查询账簿详情，并使用正确的参数名
    const response = await GiftApi.queryAccountBookDetail({
      accountBookId: id
    });
    
    if (response.code === 0 && response.data) {
      const bookData = response.data;
      
      // 使用setTimeout确保在下一个事件循环中更新数据，避免可能的响应式问题
      setTimeout(() => {
        // 设置礼簿类型
        giftType.value = bookData.transactionType === 'IN' ? '收礼礼簿' : '送礼礼簿';
        
        // 设置礼簿名称 - 直接赋值，不使用短路运算符
        if (bookData.bookName !== undefined && bookData.bookName !== null) {
          giftTitle.value = String(bookData.bookName);
        } else {
          giftTitle.value = '';
        }
        
        // 处理日期 - 确保日期格式正确
        if (bookData.eventDate) {
          try {
            const eventDate = new Date(Number(bookData.eventDate));
            giftDate.value = formatDate(eventDate);
          } catch (e) {
            console.error('日期格式化错误:', e);
            giftDate.value = formatDate(new Date());
          }
        } else {
          giftDate.value = formatDate(new Date());
        }
        
        // 处理颜色 - 直接使用颜色代码查找对应的颜色名称
        if (bookData.coverColor) {
          const colorName = getColorName(bookData.coverColor);
          selectedColor.value = colorName;
        }
        
        // 设置备注 - 直接赋值，不使用短路运算符
        if (bookData.remark !== undefined && bookData.remark !== null) {
          remark.value = String(bookData.remark);
        } else {
          remark.value = '';
        }
        
        // 强制更新视图
        uni.hideLoading();
      }, 0);
    } else {
      uni.showToast({
        title: response.msg || '获取礼簿详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取礼簿详情失败:', error);
    uni.showToast({
      title: '获取礼簿详情失败',
      icon: 'none'
    });
  }
};

// 根据颜色代码获取颜色名称
const getColorName = (colorCode) => {
  // 确保颜色代码是小写的，以便匹配
  const code = String(colorCode).toLowerCase();
  
  const colorMap = {
    '#ff4d4f': 'red',
    '#ff7a45': 'orange',
    '#52c41a': 'green',
    '#1890ff': 'blue',
    '#722ed1': 'purple',
    '#8c8c8c': 'gray',
    '#ff85c0': 'pink',
    '#13c2c2': 'teal',
    '#faad14': 'gold'
  };
  
  // 尝试直接匹配
  if (colorMap[code]) {
    return colorMap[code];
  }
  
  // 如果没有直接匹配，尝试查找最接近的颜色
  for (const [key, value] of Object.entries(colorMap)) {
    if (code.includes(key.substring(1)) || key.includes(code.substring(1))) {
      return value;
    }
  }
  
  // 默认返回红色
  return 'red';
};
</script>

<style lang="scss" scoped>
.edit-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx; /* 为底部按钮留出空间 */
}

/* 移除旧的导航栏样式 */

.form-content {
  padding: 20rpx 0;
  background-color: #fff;
  margin-top: 20rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx 40rpx;
  border-bottom: 1px solid #f5f5f5;
}

.form-label {
  width: 180rpx;
  font-size: 28rpx;
  color: #333;
}

.form-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 28rpx;
  color: #666;
}

.form-value input {
  width: 100%;
  height: 60rpx;
  font-size: 28rpx;
}

.color-selector {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.color-option {
  width: 60rpx;
  height: 60rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-right: 20rpx;
  margin-bottom: 10rpx;
}

.color-option.active::after {
  content: '';
  position: absolute;
  top: -4rpx;
  left: -4rpx;
  right: -4rpx;
  bottom: -4rpx;
  border: 2rpx solid rgba(0, 0, 0, 0.2);
  border-radius: 12rpx;
}

.tips-text {
  padding: 30rpx 40rpx;
  font-size: 24rpx;
  color: #999;
  line-height: 1.5;
}

/* 修改底部按钮区域样式 */
.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 120rpx; /* 增加高度 */
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  padding: 20rpx 30rpx;
  box-sizing: border-box;
}

.delete-btn {
  flex: 1;
  height: 100%;
  background-color: #ff4d4f;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx; /* 增大字体 */
  border-radius: 50rpx;
  margin-right: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 77, 79, 0.3);
}

.delete-btn uni-icons {
  margin-right: 10rpx;
  /* 增大图标尺寸 */
  transform: scale(1.2);
}

.placeholder {
  flex: 1;
  background-color: transparent;
  margin-right: 20rpx;
}

.confirm-btn {
  flex: 2;
  height: 100%;
  background-color: #f56c6c;
  color: #fff;
  font-size: 36rpx; /* 增大字体 */
  font-weight: 500; /* 添加字体粗细 */
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50rpx;
  box-shadow: 0 4rpx 12rpx rgba(245, 108, 108, 0.3);
}

/* 文本域样式 */
.textarea-item {
  align-items: flex-start;
  padding-top: 20rpx;
}

.form-value textarea {
  width: 100%;
  height: 160rpx;
  font-size: 28rpx;
  padding: 10rpx;
  box-sizing: border-box;
  border: none;
  border-radius: 0;
}
</style>